package cn.lds.j375.chlm.serivce.impl;

import cn.lds.j375.chlm.dto.ChlmConstant;
import cn.lds.j375.chlm.dto.ResultDTO;
import cn.lds.j375.chlm.entity.Menu;
import cn.lds.j375.chlm.exception.ChlmException;
import cn.lds.j375.chlm.mapper.MenuMapper;
import cn.lds.j375.chlm.serivce.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public ResultDTO<List<Menu>> selectMenuAll() throws ChlmException {

        List<Menu> menus = menuMapper.selectMenuAll();

        if (CollectionUtils.isEmpty(menus)){
//            throw new ChlmException(ChlmConstant.MenuMsg.QUERYERROR);
        }


        return ResultDTO.buildSuccess(menus);
    }

    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    @Override
    public ResultDTO<Menu> selectMenuById(Integer id) throws ChlmException {

        Menu menu = menuMapper.selectMenuById(id);

        if (Objects.isNull(menu)){
            throw new ChlmException(ChlmConstant.MenuMsg.QUERYERROR);
        }

        return ResultDTO.buildSuccess(menu);
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public ResultDTO addMenu(Menu menu) throws ChlmException {

        if (Objects.isNull(menu)){
            throw new ChlmException(ChlmConstant.MenuMsg.PARAMERROR);
        }

        int i = menuMapper.addMenu(menu);
        if (i <=0){
            throw new ChlmException(ChlmConstant.MenuMsg.ADD_ERROR);
        }

        return ResultDTO.buildSuccess();
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public ResultDTO modifyMenu(Menu menu) throws ChlmException {

        if (Objects.isNull(menu)){
            throw new ChlmException(ChlmConstant.MenuMsg.PARAMERROR);
        }

        int i = menuMapper.modifyMenu(menu);
        if (i <=0){
            throw new ChlmException(ChlmConstant.MenuMsg.ADD_ERROR);
        }

        return ResultDTO.buildSuccess();
    }

    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    @Override
    public ResultDTO removeMenuById(Integer id) throws ChlmException {

        int i = menuMapper.removeMenuById(id);

        if (i <=0 ){
            throw new ChlmException(ChlmConstant.MenuMsg.ADD_ERROR);
        }

        return ResultDTO.buildSuccess();
    }
}
